#!/usr/bin/env python

import xml.parsers.expat
import os

class Settings(object):
    defn = []
    stack = []
    fLoc = "/Users/jake/Dropbox/Titanium Studio Workspace/FPV/dist/osx/FPV.app/Contents/Resources/settings.xml"
    
    @staticmethod
    def getAttr(attr):
        if len(Settings.defn)==0:
            Settings.gather()
        for x in Settings.defn:
            if x[0] == attr:
                return x[1]
        return None
    
    @staticmethod
    def gather():
        Settings.defn = []
        f = open(Settings.fLoc)
        p = xml.parsers.expat.ParserCreate()
        p.StartElementHandler = Settings._start_element
        p.EndElementHandler = Settings._end_element
        p.CharacterDataHandler = Settings._char_data
        p.Parse(f.read(),1)
        f.close()
        
    @staticmethod
    def _start_element(name, attrs):
        name = str(name)
        Settings.stack.append(name)
        
    @staticmethod
    def _end_element(name):
        name = str(name)
        if Settings.stack[-1]==name:
            Settings.stack.pop()
        else:
            print "Invalid termination for tag: "+stack[-1]+" with tag: "+name
    
    @staticmethod
    def _char_data(data):
        data = str(data)
        equals = Settings._internalSolve(data).strip(" \t\n")
        if len(equals)>0:
            place = Settings.stack[1]
            for x in Settings.stack[2:]:
                place += "/"+x
            Settings.defn.append((place,equals))
         
    @staticmethod   
    def _internalSolve(rr):
        while rr.find("$$") != -1:
            temp = rr.split("$$")
            ans = None
            for x in Settings.defn:
                if x[0] == temp[1]:
                    ans = x[1]
            rr = temp[0]+str(ans)+temp[2]
            for x in xrange(3,len(temp)):
                rr += "$$" + temp[x]
        return rr
    
if len(Settings.defn) == 0:
    Settings.gather()